import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useMenuStore = defineStore('menu', () => {
  const activeTop = ref('Dashboard')
  // currently selected side menu item URL (to remember last clicked item)
  // try to restore last active side menu item from localStorage
  const STORAGE_KEY = 'app.menu.activeItem'
  const initialActive = (() => {
    try { return localStorage.getItem(STORAGE_KEY) || '' } catch (e) { return '' }
  })()
  const activeItem = ref(initialActive)
  // whether the left sidebar should be shown
  // default to hidden so login lands on dashboard without left menu
  const showSidebar = ref(false)

  function setActiveTop(name: string) {
    activeTop.value = name
  }

  function setActiveItem(url: string) {
    activeItem.value = url || ''
    try { localStorage.setItem(STORAGE_KEY, activeItem.value) } catch (e) {}
  }

  function setShowSidebar(visible: boolean) {
    showSidebar.value = visible
  }

  return { activeTop, activeItem, showSidebar, setActiveTop, setActiveItem, setShowSidebar }
})

export default useMenuStore
